package com.elective.courseselect.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elective.courseselect.dao.ScheduleDao;
import com.elective.courseselect.entity.ScheduleEntity;
import com.elective.courseselect.service.ScheduleService;
import com.elective.courseselect.utils.R;
import com.elective.status.StatusCode;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author lee
 * @date 2021年10月24日 12:15
 */
@Service("ScheduleService")
public class ScheduleServiceImpl extends ServiceImpl<ScheduleDao, ScheduleEntity> implements ScheduleService {
    @Override
    public ScheduleEntity searchSchedule() {
        ScheduleEntity scheduleEntity = new ScheduleEntity();
        for (ScheduleEntity res : this.list()) {
            return scheduleEntity = res;
        }
        return scheduleEntity;
    }

    @Override
    public R updateSchedule(ScheduleEntity scheduleEntity) {
        Date prepareTimeStart = scheduleEntity.getPrepareTimeStart();
        Date prepareTimeEnd = scheduleEntity.getPrepareTimeEnd();
        List<ScheduleEntity> list = this.list();
        for (ScheduleEntity entity : list) {
            scheduleEntity.setId(entity.getId());
        }
        if (prepareTimeStart.after(prepareTimeEnd)) {
            return R.error(StatusCode.ERROR, "预选开始时间大于结束时间,请重新设置");
        }

        Date selectTimeStart = scheduleEntity.getSelectTimeStart();
        Date selectTimeEnd = scheduleEntity.getSelectTimeEnd();
        if (selectTimeStart.after(selectTimeEnd)) {
            return R.error(StatusCode.ERROR, "选课开始时间大于结束时间,请重新设置");
        }

        if (selectTimeStart.before(prepareTimeEnd)) {
            return R.error(StatusCode.ERROR, "抢课开始时间早于预选课时间,请重新设置");
        }

        this.updateById(scheduleEntity);
        return R.ok(StatusCode.OK, "修改时间段成功");
    }

    @Override
    public R addSchedule(ScheduleEntity scheduleEntity) {
        List<ScheduleEntity> list = this.list();
        if (!list.isEmpty()) {
            return R.error(StatusCode.ERROR, "已有选课时间,无法再次新增");
        }
        this.save(scheduleEntity);
        return R.ok(StatusCode.OK, "增加时间段成功");
    }
}
